<template>
  <div class=''>
    <!-- 面包屑导航区域 -->
    <Bootstrap v-bind:BootstrapTitle="BootstrapTitle"></Bootstrap>
    <!-- 面包屑导航区域end -->
    <!-- 卡片 -->
    <el-card>
      <!-- 警告 -->
      <el-alert :closable="false" title="注意：只允许为第三级分类设置相关参数！" type="warning" center show-icon>
      </el-alert>
      <!-- 商品选择 -->
      <el-row class="el-header">
        <el-col class="el-ccc">
          <span>选择商品分类: </span>
          <el-cascader v-model="selecterCateKeys" expandTrigger='hover' :options="cateList" :props="cateProps"
            @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="tabhandleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button size="mini" type="warning" class="el-btn" :disabled="isBtnDisabled" @click="addBtn">添加参数
          </el-button>
          <!-- 表格 -->
          <el-table :data="manyData" style="width: 100%" border stripe>
            <el-table-column type="expand" prop="date" label="" width="50">
              <template slot-scope="scope">
                <!-- 标签 -->
                <el-tag size="small" @close="handleClose(i,scope.row)" closable class="tags"
                  v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}
                </el-tag>
                <!-- 按钮切换 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="" width="50">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="xiugaiBtn(scope.row.attr_id)">编辑
                </el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="DeleteBtn(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="静态属性" name="only">

          <el-button size="mini" type="warning" class="el-btn" :disabled="isBtnDisabled" @click="addBtn">添加属性
          </el-button>
          <!-- bg/2 -->
          <el-table :data="onlyData" style="width: 100%" border stripe>
             <el-table-column type="expand" prop="date" label="" width="50">
              <template slot-scope="scope">
                <!-- 标签 -->
                <el-tag size="small" @close="handleClose(i,scope.row)" closable class="tags"
                  v-for="(item,i) in scope.row.attr_vals" :key="i">{{item}}
                </el-tag>
                <!-- 按钮切换 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="" width="50">
            </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="xiugaiBtn(scope.row.attr_id)">编辑
                </el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="DeleteBtn(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
      </el-tabs>
      <!-- add对话框 -->
      <el-dialog :title="activeName ==='many'?'添加动态参数':'添加静态属性' " :visible.sync="adddialogVisible" width="30%"
        @close="addDialogClosed">
        <el-form :model="addForm" :rules="addrules" ref="addruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item :label="activeName ==='many'?'动态参数':'静态属性'" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="adddialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改对话框  -->
      <el-dialog :title="activeName ==='many'?'修改动态参数':'修改静态属性' " :visible.sync="xiugaidialogVisible" width="30%"
        @close="xiugaiDialogClosed">
        <el-form :model="xiugaiForm" :rules="xiugairules" ref="xiugairuleForm" label-width="100px"
          class="demo-ruleForm">
          <el-form-item :label="activeName ==='many'?'动态参数':'静态属性'" prop="attr_name">
            <el-input v-model="xiugaiForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="xiugaidialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="xiugaiParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 卡片end -->
  </div>
</template>
<script>
import Bootstrap from "../../component/component/Bootstrap";
export default {
  name: "",
  components: {
    Bootstrap,
  },
  data() {
    return {
      BootstrapTitle: {
        first: "商品管理",
        second: "/params",
        third: " 分类参数",
      },
      // 级联选择器数据
      cateList: [],
      // 选择框配置对象
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      selecterCateKeys: [],
      activeName: "many",
      isY: "false",
      manyData: [],
      onlyData: [],
      adddialogVisible: false,
      xiugaidialogVisible: false,
      addForm: {},
      xiugaiForm: {},
      addrules: {
        attr_name: [{ required: true, message: "请输入参数", trigger: "blur" }],
      },
      xiugairules: {
        attr_name: [{ required: true, message: "请输入参数", trigger: "blur" }],
      },
      attrId: "",
    };
  },
  created() {
    this.getClassificaGoods();
  },
  methods: {
    async getClassificaGoods() {
      let res = await this.$http.get("categories");
      if (res.data.meta.status !== 200) {
        return this.$message.error(res.data.meta.msg);
      } else {
        this.cateList = res.data.data;
        this.$message.success(res.data.meta.msg);
      }
    },
    // handleChange
    async handleChange() {
      this.getParamsData();
    },
    async getParamsData() {
      if (this.selecterCateKeys.length !== 3) {
        this.selecterCateKeys = [];
        this.manyData=[]
        this.onlyData=[]
        return;
      } else {
        let res = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: this.activeName },
        });
        if (res.data.meta.status != 200) {
          return this.$message.error(res.data.meta.msg);
        } else {
          res.data.data.forEach((item) => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
            item.inputVisible = false;
            item.inputValue = "";
          });
          this.$message.success(res.data.meta.msg);
          if (this.activeName === "many") {
            this.manyData = res.data.data;
          } else {
            this.onlyData = res.data.data;
          }
        }
      }
    },
    // tabhandleClick
    tabhandleClick() {
      this.getParamsData();
      // console.log(this.activeName);
    },
    // addBtn
    addBtn() {
      this.adddialogVisible = true;
    },
    // addDialogClosed
    addDialogClosed() {
      this.$refs.addruleForm.resetFields();
    },
    // xiugaiDialogClosed
    xiugaiDialogClosed() {
      this.$refs.xiugairuleForm.resetFields();
    },
    // addParams
    addParams() {
      this.$refs.addruleForm.validate(async (valid) => {
        if (!valid) {
          return;
        } else {
          let res = await this.$http.post(
            `categories/${this.cateId}/attributes`,
            {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName,
            }
          );
          if (res.data.meta.status !== 201)
            return this.$message.error(res.data.meta.msg);
          this.$message.success(res.data.meta.msg);
          this.getParamsData();
          this.adddialogVisible = false;
        }
      });
    },
    // xiugaiParams
    xiugaiParams() {
      this.$refs.xiugairuleForm.validate(async (valid) => {
        if (!valid) {
          return;
        } else {
          let res = await this.$http.put(
            `categories/${this.cateId}/attributes/${this.attrId}`,
            {
              attr_name: this.xiugaiForm.attr_name,
              attr_sel: this.activeName,
            }
          );
          if (res.data.meta.status !== 200)
            return this.$message.error(res.data.meta.msg);
          this.$message.success(res.data.meta.msg);
          this.getParamsData();
          this.xiugaidialogVisible = false;
        }
      });
    },
    // xiugaiBtn按钮
    xiugaiBtn(attrId) {
      // console.log(row, "213131321");
      this.attrId = attrId;
      this.xiugaidialogVisible = true;
    },
    // DeleteBtn
    async DeleteBtn(id) {
      let confirm = await this.$confirm(
        "操作将永久删除该参数/属性, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirm !== "confirm") {
        this.$message.error("取消删除");
      } else {
        let res = await this.$http.delete(
          `categories/${this.cateId}/attributes/${id}`
        );
        if (res.data.meta.status !== 200) {
          return this.$message.error(res.data.meta.msg);
        }
        this.$message.success(res.data.meta.msg);
        this.getParamsData();
      }
    },
    // handleInputConfirm
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      let res = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(","),
        }
      );
      if (res.data.meta.status !== 200)
        return this.$message.error(res.data.meta.msg);
      this.$message.success(res.data.meta.msg);
    },
    // showInput
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // handleClose
  async  handleClose(i,row) {
      row.attr_vals.splice(i,1)
       let res = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(","),
        }
      );
      if (res.data.meta.status !== 200)
        return this.$message.error(res.data.meta.msg);
      this.$message.success(res.data.meta.msg);
    },
  },
  computed: {
    isBtnDisabled() {
      if (this.selecterCateKeys.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    cateId() {
      if (this.selecterCateKeys.length === 3) {
        return this.selecterCateKeys[2];
      } else {
        return null;
      }
    },
  },
};
</script>
<style lang='less' scoped>
.el-header {
  margin: 15px 0 15px 0;
}
.el-btn {
  background-color: #ffcc33;
  border: 0;
  color: #606266;
}
.el-ccc {
  margin-left: -18px;
}
.tags {
  margin: 0 10px;
}
.input-new-tag {
  width: 120px;
}
</style>